package com.eric.media;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.VideoView;

import com.eric.media.utils.LocalVideoUtil;
import com.eric.media.utils.VideoPlayUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@EActivity(R.layout.activity_video_view)
public class VideoViewActivity extends AppCompatActivity {

    @ViewById
    VideoView video_view;
    /** 视频播放地址*/
    private String videoPath ;
    /**本地视频地址*/
    Map<String , Bitmap> localVideoPath = new HashMap<String, Bitmap>();
    @AfterViews
    void initData(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //动态判断手机储存空间的权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == -1 ||
                    ActivityCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE ) == -1){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE},0x123);
            }else {
                getLocalVideos();
            }
        }else {
            getLocalVideos();
        }
    }

    /**
     * 获取本地视频
     */
    private void getLocalVideos(){
        localVideoPath.putAll(LocalVideoUtil.getVideoMapThumbnail(this, getContentResolver()));
        Set<Map.Entry<String,Bitmap>> entries = localVideoPath.entrySet();
        Iterator<Map.Entry<String,Bitmap>> iterator = entries.iterator();
        while (iterator.hasNext()){
            Map.Entry<String,Bitmap> item = iterator.next();
            videoPath =  item.getKey();
        }
        if (!TextUtils.isEmpty(videoPath)){
            VideoPlayUtil.playByVideoView(video_view,videoPath,this,true);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x123){
            if (grantResults[0] == 0 && grantResults[1] == 0){
                getLocalVideos();
            }
        }
    }


}
